function [M] = knn2lle(nn,X)

[n,k] = size(nn);
W = zeros(n,k);
for i=1:n
    Xn = X(nn(i,:),:);
    z = Xn - repmat(X(i,:),k,1);
    C = z*z';
    %C = C + tol*trace(C)*eye(K)/K; % REGULARIZATION
    invC = inv(C);
    W(i,:) = sum(invC)/sum(sum(invC));
end

ivec = repmat((1:n)',k,1);
nvec = reshape(nn,[],1);
wvec = reshape(W,[],1);

B = sparse(1:n,1:n,1) - sparse(ivec,nvec,wvec,n,n);
M = B'*B;
end